using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using System.Diagnostics;
using System.Windows.Forms;
using Sunny.UI.Win32;
using System.Runtime.InteropServices;
using System.Windows.Navigation;
using Microsoft.Win32;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;
using WinformDevFramework.Services;

namespace WinformDevFramework
{
    public partial class FrmW_Goods : BaseForm1
    {
        private IW_GoodsServices _W_GoodsServices;
        private IsysDicDataServices _SysDicDataServices;
        private Iw_BuyDetailServices _W_BuyDetailServices;
        public FrmW_Goods(IW_GoodsServices W_GoodsServices,IsysDicDataServices sysDicDataServices, Iw_BuyDetailServices w_BuyDetailServices)
        {
            _W_GoodsServices = W_GoodsServices;
            _SysDicDataServices = sysDicDataServices;
            InitializeComponent();
            _W_BuyDetailServices = w_BuyDetailServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();
            GoodsType.DataSource = _SysDicDataServices.QueryListByClause(p => p.DicTypeID == 1002).Select(p=>p.DicData).ToList();
            GoodsUnit.DataSource = _SysDicDataServices.QueryListByClause(p => p.DicTypeID == 1003).Select(p => p.DicData).ToList();
            // 设置隐藏列
            this.dataGridViewList.Columns["GoodsCode"].HeaderText = "商品编号";
            this.dataGridViewList.Columns["GoodsName"].HeaderText = "商品名称";
            this.dataGridViewList.Columns["GoodsSpec"].HeaderText = "规格型号";
            this.dataGridViewList.Columns["GoodsType"].HeaderText = "商品类别";
            this.dataGridViewList.Columns["GoodsUnit"].HeaderText = "计量单位";
            this.dataGridViewList.Columns["RestockingPrice"].HeaderText = "进货价";
            this.dataGridViewList.Columns["RetailPrice"].HeaderText = "零售价";
            this.dataGridViewList.Columns["WholesalePrice"].HeaderText = "批发价";
            this.dataGridViewList.Columns["SafetyStock"].HeaderText = "安全库存";
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["GoodsImages"].HeaderText = "商品图片";
            this.dataGridViewList.Columns["GoodsImages"].Visible = false;
            this.dataGridViewList.Columns["Stock"].HeaderText = "库存";

            this.GoodsNameD.DataSource = _W_GoodsServices.Query();
            this.GoodsNameD.DisplayMember = "GoodsName";
            this.GoodsNameD.ValueMember = "GoodsCode";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as W_Goods;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();           
            this.GoodsCode.Text = model.GoodsCode;  
            this.GoodsName.Text = model.GoodsName;  
            this.GoodsSpec.Text = model.GoodsSpec;  
            this.GoodsType.Text = model.GoodsType;  
            this.GoodsUnit.Text = model.GoodsUnit;  
            this.RestockingPrice.Text = model.RestockingPrice.ToString();  
            this.RetailPrice.Text = model.RetailPrice.ToString();  
            this.WholesalePrice.Text = model.WholesalePrice.ToString();  
            this.SafetyStock.Text = model.SafetyStock.ToString();
            this.Remark.Text = model.Remark; 
            this.GoodsImages.Tag = model.GoodsImages;
            if(!string.IsNullOrEmpty(model.GoodsImages))
                this.GoodsImages.Image = Base64ToImage(model.GoodsImages);
            else
            {
                this.GoodsImages.Image = null;
            }
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            GoodsCode.ReadOnly = true;

        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    W_Goods model = new W_Goods();
                    // TODO获取界面的数据
                    model.GoodsCode=this.GoodsCode.Text;
                    model.GoodsName=this.GoodsName.Text;
                    model.GoodsSpec=this.GoodsSpec.Text;
                    model.GoodsType=this.GoodsType.Text;
                    model.GoodsUnit=this.GoodsUnit.Text;
                    model.RestockingPrice=this.RestockingPrice.Value;
                    model.RetailPrice=this.RetailPrice.Value;
                    model.WholesalePrice=this.WholesalePrice.Value;
                    model.SafetyStock=this.SafetyStock.Value;
                    model.Remark=this.Remark.Text;
                    model.GoodsImages=this.GoodsImages.Tag?.ToString();
                    var id = _W_GoodsServices.Insert(model);
                    txtID.Text = id.ToString();
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                // 修改
                else
                {
                    W_Goods model = _W_GoodsServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.GoodsCode=this.GoodsCode.Text;
                    model.GoodsName=this.GoodsName.Text;
                    model.GoodsSpec=this.GoodsSpec.Text;
                    model.GoodsType=this.GoodsType.Text;
                    model.GoodsUnit=this.GoodsUnit.Text;
                    model.RestockingPrice=this.RestockingPrice.Value;
                    model.RetailPrice=this.RetailPrice.Value;
                    model.WholesalePrice=this.WholesalePrice.Value;
                    model.SafetyStock=this.SafetyStock.Value;
                    model.Remark=this.Remark.Text;
                    model.GoodsImages=this.GoodsImages.Tag?.ToString();
                    if (_W_GoodsServices.Update(model))
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _W_GoodsServices.DeleteById(Int32.Parse(txtID.Text));
                formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        dataGridViewBuyDetail.Rows.Clear();
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        SetDataToBuyDetail(_W_BuyDetailServices.QueryListByClause(p=>p.GoodsCode==GoodsCode.Text));
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        dataGridViewBuyDetail.Rows.Clear();
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            if (string.IsNullOrEmpty(GoodsCode.Text))
            {
                MessageBox.Show("商品编号不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(GoodsName.Text))
            {
                MessageBox.Show("商品名称不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(GoodsType.Text))
            {
                MessageBox.Show("商品类别不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(GoodsUnit.Text))
            {
                MessageBox.Show("计量单位不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(RestockingPrice.Text))
            {
                MessageBox.Show("进货价不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(RetailPrice.Text))
            {
                MessageBox.Show("零售价不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(WholesalePrice.Text))
            {
                MessageBox.Show("批发价不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(SafetyStock.Text))
            {
                MessageBox.Show("安全库存不能为空！");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<W_Goods> GetData()
        {
            List<W_Goods> data = new List<W_Goods>();
            data = _W_GoodsServices.Query();
            return data;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp";
            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 检查图像大小
                FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                long fileSize = fileInfo.Length;

                if (fileSize > 1024 * 1024) // 1MB = 1024 * 1024 bytes
                {
                    MessageBox.Show("图片大小不能超过1MB");
                    return;
                }
                Image image =Image.FromFile(openFileDialog.FileName);
                GoodsImages.Image=image;
                var str= ImageToBase64(image);
                GoodsImages.Tag = str;
            }
        }
        private string ImageToBase64(Image image)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, image.RawFormat);
                byte[] imageBytes = memoryStream.ToArray();
                return Convert.ToBase64String(imageBytes);
            }
        }
        private Image Base64ToImage(string base64str)
        {
            byte[] imageBytes = Convert.FromBase64String(base64str);
            using (MemoryStream memoryStream = new MemoryStream(imageBytes))
            {
                return Image.FromStream(memoryStream);
            }
        }

        private void GoodsImages_DoubleClick(object sender, EventArgs e)
        {
            if (GoodsImages.Image  == null)
            {
                return;
            }
            // 获取PictureBox控件中的图片
            byte[] imageBytes = Convert.FromBase64String(GoodsImages.Tag.ToString());
            // 保存图片到临时文件
            string tempFilePath = Application.StartupPath + $"goods.{GoodsImages.Image.RawFormat}";
            File.WriteAllBytes(tempFilePath, imageBytes);
            //建立新的系统进程    
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            //设置图片的真实路径和文件名    
            process.StartInfo.FileName = tempFilePath;

            //设置进程运行参数，这里以最大化窗口方法显示图片。    
            process.StartInfo.Arguments = "rundl132.exe C://WINDOWS//system32//shimgvw.dll,ImageView_Fullscreen";

            //此项为是否使用Shell执行程序，因系统默认为true，此项也可不设，但若设置必须为true    
            process.StartInfo.UseShellExecute = true;

            //此处可以更改进程所打开窗体的显示样式，可以不设    
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            process.Start();
            process.Close();
            // 删除临时文件
            //File.Delete(tempFilePath);
        }
        /// <summary>
        /// 明细表 购货设置数据
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToBuyDetail(List<w_BuyDetail> details)
        {
            dataGridViewBuyDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewBuyDetail.Rows.AddCopy(dataGridViewBuyDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewBuyDetail.Rows[dataGridViewBuyDetail.Rows.Count - 2];
                row.Cells["BuyNumber"].Value = p.BuyNumber;
                row.Cells["GoodsNameD"].Value = p.GoodsCode;
                row.Cells["GoodsCodeD"].Value = p.GoodsCode;
                row.Cells["UnitPrice"].Value = p.UnitPrice;
                row.Cells["DiscountPrice"].Value = p.DiscountPrice;
                row.Cells["TotalPriceD"].Value = p.TotalPrice;
                row.Cells["TaxRate"].Value = p.TaxRate;
                row.Cells["TaxUnitPrice"].Value = p.TaxUnitPrice;
                row.Cells["TaxPrice"].Value = p.TaxPrice;
                row.Cells["TotalTaxPrice"].Value = p.TotalTaxPrice;
                row.Cells["RemarkD"].Value = p.Remark;
                row.Cells["TotalTaxPrice"].Value = p.TotalTaxPrice;
                row.Cells["BuyID"].Value = p.BuyID;
                row.Cells["BuyCodeD"].Value = p.BuyCode;
                row.Cells["BuyDetailCode"].Value = p.BuyDetailCode;
            });
        }
    }
}
